import React, {
    PureComponent
} from 'react';

import {
    View,
    Dimensions,
    StyleSheet
} from 'react-native';

import WebView from 'react-native-webview';

import {
    Loading
} from './../../components';

const {
    width,
    height
} = Dimensions.get('window');

import Ajax from './../../http';

import {
    Type
} from './index'

import getUrlParams from './../../utils/getUrlParams';

interface State {
    uri: string,
    loading: boolean
}

interface Props {
    type:Type,
    planId:string,
    onSuccess: Function,
    onCancel: Function,
    onError: Function,
    onDialogClose:Function
}

const returnUrl = `http://paypal.secret.returnurl.com`;
const cancelUrl = `http://paypal.secret.cancelurl.com`;

class Content extends PureComponent<Props, State> {
    state = {
        uri: ``,
        loading: true
    }

    complete: boolean = false;

    static defaultProps = {
        planId:``,
        type:`consumable`,
        onError: () => null,
        onCancel: () => null,
        onSuccess: () => null,
        onDialogClose:() => null
    }

    componentDidMount() {
        this.start();
    }

    public start = async () => {
        const {
            type,
            planId,
            onError
        } = this.props;
        const para = {
            returnUrl: returnUrl,
            cancelUrl: cancelUrl,
            productIdentifier: planId,
        }
        const _url = (
            `paypal/${type}/approve`
        )
        try {
            const {
                approveUrl
            } = await Ajax.post(
                _url, para
            )
            this.setState({
                uri: approveUrl
            })
        }
        catch (e) {
            onError(e);
            this.onClose();
        }
    }

    private onLoadError = () => {
        const {
            onError
        } = this.props;
        this.onClose();
        onError({ message:`Load error.` })
    }

    private onLoadEnd = () => {
        this.setState({
            loading: false
        })
    }

    private onNavChange = ({url}:any) => {
        //成功
        if (url.includes(returnUrl)) {
            if (!this.complete) {
                this.onUserAgree(url);
            }
        }
        //取消
        if (url.includes(cancelUrl)) {
            if (!this.complete) {
                this.onUserCancel();
            }
        }
    }

    private onUserAgree = (url: string) => {
        this.complete = true;
        this.props.onSuccess(
            getUrlParams(`token`, url)
        )
        this.onClose();
    }

    private onUserCancel = () => {
        this.complete = true;
        this.onClose();
    }

    private onClose = () => {
        this.props.onDialogClose();
    }

    render() {
        const {
            uri,
            loading
        } = this.state;
        return (
            <View style={styles.container}>
                {!!uri ? (
                    <WebView
                        cacheEnabled={true}
                        source={{uri: uri}}
                        style={styles.webView}
                        allowFileAccess={true}
                        originWhitelist={[`*`]}
                        onError={this.onLoadError}
                        onLoadEnd={this.onLoadEnd}
                        onNavigationStateChange={this.onNavChange}
                    />
                ) : null}
                {loading && (
                    <View style={styles.mask}>
                        <Loading.container/>
                    </View>
                )}
            </View>
        )
    }
}

export default Content;

const styles: any = StyleSheet.create({
    container: {
        width:width,
        height: height
    },
    webView: {
        flex: 1,
        backgroundColor: `#f2f2f2`
    },
    mask: {
        left:0,
        right:0,
        top:0,
        bottom:0,
        position:`absolute`
    }
});